<!-- #layout name=blank -->
<div id="app" v-cloak>
  <div class="page-header">
    <h1 class="title">Pages</h1>
  </div>

  <kb-breadcrumb :breads="breads"></kb-breadcrumb>

  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a
        class="btn green navbar-btn"
        :href="Kooboo.Route.Get(Kooboo.Route.Page.EditPage)"
        >New page</a
      >
      <a
        class="btn green navbar-btn"
        :href="Kooboo.Route.Get(Kooboo.Route.Page.EditRichText)"
        >New rich text page</a
      >
      <div class="btn-group navbar-btn">
        <button class="btn green" data-toggle="dropdown">
          <span>New layout page</span> <i class="fa fa-angle-down"></i>
        </button>
        <ul class="dropdown-menu">
          <li v-for="(item,index) in layouts">
            <a :href="item.href">{{ item.name }}</a>
          </li>
        </ul>
      </div>
      <a class="btn green navbar-btn" @click="showImportModal=true">Import</a>
      <a
        class="btn green navbar-btn"
        @click="showCopyModal=true"
        v-show="selectedRows.length==1"
        >Copy</a
      >
      <a
        class="btn red navbar-btn"
        v-show="selectedRows.length>0"
        @click="onDelete"
        >Delete</a
      >
      <a
        href="javascript:;"
        class="btn btn-default navbar-btn pull-right"
        style="margin-right:0"
        v-kb-tooltip:left="Kooboo.text.tooltip.pageRouterManager"
        @click="showRouterManagerModal=true"
        ><i class="fa fa-gear"></i
      ></a>
    </div>
  </div>

  <kb-table
    v-if="model.pages"
    :data="model.pages"
    show-select
    :selected.sync="selectedRows"
  >
    <kb-table-column width="40px">
      <template v-slot="row">
        <i class="fa fa-home fa-lg" v-show="row.startPage"></i>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.name" prop="name">
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.page.linked">
      <template v-slot="row">
        <span class="badge badge-primary">
          {{ row.linked }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.page.online">
      <template v-slot="row">
        <span :class="onlineClass(row.online)">
          {{ row.online ? Kooboo.text.online.yes : Kooboo.text.online.no }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.page.references">
      <template v-slot="row">
        <a
          class="label label-sm kb-table-label-refer"
          :style="{
                background: Kooboo.getLabelColor(item.key.toLowerCase())
              }"
          v-for="(item, index) in Kooboo.objToArr(row.relations)"
          :key="index"
          @click.stop="onShowRelationModal(item.key, row.id, Kooboo.Page.name)"
        >
          {{ item.value + " " +
          Kooboo.text.component.table[item.key.toLowerCase()] }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span>
          {{ new Date(row.lastModified).toDefaultLangString() }}
        </span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.preview">
      <template v-slot="row">
        <a :href="row.previewUrl" @click.stop="" target="_blank">
          {{ row.path }}
        </a>
      </template>
    </kb-table-column>

    <kb-table-column align="right" width="200px">
      <template v-slot="row">
        <a class="btn blue" @click.stop="settingClick(row)"
          >{{ Kooboo.text.common.setting }}</a
        >
        <a
          class="btn btn-primary"
          @click.stop=""
          :href="row.inlineUrl"
          target="_blank"
          >{{ Kooboo.text.site.page.design }}</a
        >
      </template>
    </kb-table-column>

    <kb-table-column width="10px">
      <template v-slot="row">
        <a
          v-if="!isLocal"
          class="btn-default btn-xs"
          @click.stop="onShowQrCode(row.previewUrl)"
        >
          <i class="fa fa-qrcode"></i>
        </a>
      </template>
    </kb-table-column>
  </kb-table>

  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showImportModal"
    ref="importModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" @click="onHideImportModal">
            <i class="fa fa-close"></i>
          </button>
          <h4 class="modal-title">Import</h4>
        </div>
        <div class="modal-body">
          <kb-form
            :model="importModel"
            :rules="importModelRules"
            ref="importForm"
          >
            <kb-form-item>
              <label class="control-label col-md-3">From</label>
              <div class="col-md-9">
                <label class="radio-inline">
                  <input
                    type="radio"
                    value="url"
                    v-model="importFrom"
                  />URL</label
                >
                <label class="radio-inline">
                  <input
                    type="radio"
                    value="file"
                    v-model="importFrom"
                  />File</label
                >
              </div>
            </kb-form-item>

            <kb-form-item v-show="importFrom=='url'" prop="pageUrl">
              <label class="control-label col-md-3">Page URL</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  placeholder="Input page URL"
                  v-model="importModel.pageUrl"
                />
              </div>
            </kb-form-item>

            <kb-form-item v-show="importFrom=='url'" prop="name">
              <label class="control-label col-md-3">URL</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  placeholder="Input page path"
                  v-model="importModel.name"
                />
              </div>
            </kb-form-item>

            <kb-form-item v-show="importFrom=='file'">
              <label class="control-label col-md-3">File</label>
              <div class="col-md-9">
                <a class="btn btn-default btn-file">
                  <input
                    type="file"
                    :accept="accept"
                    @input="selectedFile($event.target.files)"
                  />
                  <span>Select file</span>
                </a>
                <span>Support types: HTML, PDF, Word, Excel, PPT, ZIP</span>
              </div>
            </kb-form-item>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button
            class="btn green"
            v-show="importFrom=='url'"
            @click="onImportSubmit"
            >Start</button
          >
          <button class="btn gray" @click="onHideImportModal">Cancel</button>
        </div>
      </div>
    </div>
  </div>

  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showCopyModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">
            <i class="fa fa-close"></i>
          </button>
          <h4 class="modal-title">{{ copyModalTitle }}</h4>
        </div>
        <div class="modal-body">
          <kb-form :model="copyModel" :rules="copyModelRules" ref="copyForm">
            <kb-form-item prop="name">
              <label class="control-label col-md-3">Name</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="copyModel.name"
                />
              </div>
            </kb-form-item>
            <kb-form-item prop="url">
              <label class="control-label col-md-3">URL</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="copyModel.url"
                />
              </div>
            </kb-form-item>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button @click="onStartCopy" class="btn green">Start</button>
          <button class="btn gray" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>

  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showRouterManagerModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" @click="showRouterManagerModal = false">
            <i class="fa fa-close"></i>
          </button>
          <h4 class="modal-title">Route setting</h4>
        </div>
        <div class="modal-body">
          <div class="form-horizontal">
            <div class="alert alert-info alert-dismissable">
              <button
                type="button"
                class="close"
                data-dismiss="alert"
                aria-label="Close"
              >
                <i class="fa fa-close"></i>
              </button>
              <strong>Redirect routes</strong>
              <p>{{ Kooboo.text.site.page.redirectRoutesTip }}</p>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Home page</label>
              <div class="col-md-9">
                <select v-model="routerModel.startPage" class="form-control">
                  <option
                    v-for="(item,index) in indexRouterSelection"
                    :key="index"
                    :value="item.id"
                    >{{ item.path }}</option
                  >
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">404 page</label>
              <div class="col-md-9">
                <select v-model="routerModel.notFound" class="form-control">
                  <option
                    v-for="(item,index) in routerSelection"
                    :key="index"
                    :value="item.id"
                    >{{ item.path }}</option
                  >
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Error page</label>
              <div class="col-md-9">
                <select v-model="routerModel.error" class="form-control">
                  <option
                    v-for="(item,index) in routerSelection"
                    :key="index"
                    :value="item.id"
                    >{{ item.path }}</option
                  >
                </select>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn green" @click="saveRouterManager">Save</button>
          <button class="btn gray" @click="showRouterManagerModal = false"
            >Cancel</button
          >
        </div>
      </div>
    </div>
  </div>

  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showQRCodeModal"
  >
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" @click="showQRCodeModal=false">
            <i class="fa fa-close"></i>
          </button>
          <h4 class="modal-title"
            >{{ Kooboo.text.site.page.previewInMobile }}</h4
          >
        </div>
        <div class="modal-body">
          <div id="qr-code" style="text-align:center"></div>
        </div>
        <div class="modal-footer">
          <button @click="showQRCodeModal=false"
            >{{ Kooboo.text.common.OK }}</button
          >
        </div>
      </div>
    </div>
  </div>
  <kb-relation-modal></kb-relation-modal>
  <div k-if="kooboosetting.IsLocal==true" id="isLocal"> </div>
</div>

<script>
  Kooboo.loadJS([
    "/_Admin/Scripts/components/kbBreadcrumb.js",
    "/_Admin/Scripts/components/kbForm.js",
    "/_Admin/Scripts/components/kbTable.js",
    "/_Admin/Scripts/components/kbRelationModal.js",
    "/_Admin/Scripts/kooboo/Guid.js",
    "/_Admin/Scripts/lib/jquery.qrcode.min.js"
  ]);

  new Vue({
    el: "#app",
    data: function() {
      var me = this;
      return {
        breads: [
          {
            name: "SITES"
          },
          {
            name: "DASHBOARD"
          },
          {
            name: Kooboo.text.common.Pages
          }
        ],
        model: {},
        selectedRows: [],
        importFrom: "url",
        importModel: {
          siteId: Kooboo.getQueryString("SiteId"),
          pageUrl: "",
          name: ""
        },
        copyModel: {
          id: "",
          name: "",
          url: ""
        },
        routerModel: {
          startPage: "",
          notFound: "",
          error: ""
        },
        copyModelRules: {
          name: [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64
            },
            {
              remote: {
                url: Kooboo.Page.isUniqueName(),
                data: function() {
                  return {
                    name: me.copyModel.name
                  };
                }
              },
              message: Kooboo.text.validation.taken
            }
          ],
          url: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^[^\s|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\||\[|\]|\;|\:|\"|\'|\,|\<|\>|\?]*$/,
              message: Kooboo.text.validation.urlInvalid
            }
          ]
        },
        importModelRules: {
          pageUrl: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/,
              message: Kooboo.text.validation.urlInvalid
            }
          ],
          name: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^[^\s|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\||\[|\]|\;|\:|\"|\'|\,|\<|\>|\?]*$/,
              message: Kooboo.text.validation.urlInvalid
            },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64
            }
          ]
        },
        showImportModal: false,
        showCopyModal: false,
        showRouterManagerModal: false,
        showQRCodeModal: false,
        showRelationModal: false,
        accept: [
          "application/pdf",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "application/vnd.ms-word.document.macroEnabled.12",
          "application/msexcel",
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          "application/vnd.ms-powerpoint",
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
          "application/x-rar-compressed",
          "application/octet-stream",
          "application/x-zip-compressed",
          "application/zip",
          "application/octet-stream",
          "text/html"
        ],
        isLocal: false
      };
    },
    computed: {
      layouts: function() {
        var list = [];

        if (this.model.layouts) {
          list = this.model.layouts.map(function(m) {
            return {
              name: m.name,
              href: Kooboo.Route.Get(Kooboo.Route.Page.EditLayout, {
                layoutId: m.id
              })
            };
          });
        }

        if (!list.length) {
          list.push({
            name: Kooboo.text.site.page.createNewLayout,
            href: Kooboo.Route.Get(Kooboo.Route.Layout.Create)
          });
        }

        return list;
      },
      routerSelection: function() {
        var arr = [
          {
            id: Kooboo.Guid.Empty,
            path: Kooboo.text.site.page.systemDefault
          }
        ];

        if (this.model.pages) {
          arr = arr.concat(this.model.pages);
        }

        return arr;
      },
      indexRouterSelection: function() {
        return this.model.pages || [];
      },
      copyModalTitle: function() {
        var text = Kooboo.text.site.page.copyPage + ": ";
        if (this.selectedRows.length == 1) {
          text += this.selectedRows[0].name;
        }
        return text;
      }
    },
    mounted: function() {
      var me = this;
      me.isLocal = document.getElementById("isLocal");
      Kooboo.Page.getAll().then(function(res) {
        if (res.success) {
          me.model = res.model;
        }
      });
    },
    methods: {
      onHideImportModal: function() {
        this.showImportModal = false;
        this.$refs.importForm.clearValid();
      },
      onImportSubmit: function() {
        if (this.$refs.importForm.validate()) {
          var me = this;
          Kooboo.Transfer.singlePage(this.importModel).then(function(res) {
            if (res.success) {
              me.model.pages.push(res.model);
              me.showImportModal = false;
              window.info.show(Kooboo.text.info.copy.success, true);
            }
          });
        }
      },
      saveRouterManager: function() {
        var me = this;
        Kooboo.Page.defaultRouteUpdate(this.routerModel).then(function(res) {
          if (res.success) {
            Kooboo.Page.getAll().then(function(res) {
              if (res.success) {
                window.info.show(Kooboo.text.info.update.success, true);
                me.model.pages = res.model.pages;
                me.showRouterManagerModal = false;
              }
            });
          }
        });
      },
      selectedFile: function(files) {
        if (files.length) {
          var formdata = new FormData();
          var me = this;
          formdata.append("file", files[0]);
          Kooboo.Page.ConvertFile(formdata).then(function(res) {
            if (res.success) {
              Kooboo.Page.getAll().then(function(res) {
                if (res.success) {
                  window.info.show(Kooboo.text.info.upload.success, true);
                  me.model.pages = res.model.pages;
                  me.showImportModal = false;
                }
              });
            }
          });
        }
      },
      onStartCopy: function() {
        if (this.$refs.copyForm.validate()) {
          var me = this;
          Kooboo.Page.Copy(this.copyModel).then(function(res) {
            if (res.success) {
              me.model.pages.push(res.model);
              window.info.show(Kooboo.text.info.copy.success, true);
              me.showCopyModal = false;
            } else {
              window.info.show(Kooboo.text.info.copy.fail, false);
            }
          });
        }
      },
      onlineClass: function(isOnline) {
        var list = ["label", "label-sm"];
        list.push(isOnline ? "label-success" : "label-default");
        return list;
      },
      settingClick: function(row) {
        var url =
          row.layoutId == Kooboo.Guid.Empty
            ? Kooboo.Route.Get(
                Kooboo.Route.Page[
                  row.type == "Normal" ? "EditPage" : "EditRichText"
                ],
                {
                  Id: row.id
                }
              )
            : Kooboo.Route.Get(Kooboo.Route.Page.EditLayout, {
                Id: row.id,
                layoutId: row.layoutId
              });
        location.href = url;
      },
      onShowQrCode: function(url) {
        $("#qr-code")
          .empty()
          .qrcode(url);
        this.showQRCodeModal = true;
      },
      onShowRelationModal: function(by, id, type) {
        Kooboo.EventBus.publish("kb/relation/modal/show", {
          by: by,
          type: type,
          id: id
        });
      },
      onDelete: function() {
        var me = this;
        var haveRelations = this.selectedRows.some(function(s) {
          return s.relations && Object.keys(s.relations).length;
        });

        var confirmStr = haveRelations
          ? Kooboo.text.confirm.deleteItemsWithRef
          : Kooboo.text.confirm.deleteItems;

        var ids = this.selectedRows.map(function(m) {
          return m.id;
        });

        if (!confirm(confirmStr)) return;

        Kooboo[Kooboo.Page.name]
          .Deletes({
            ids: ids
          })
          .then(function(res) {
            if (res.success) {
              Kooboo.Page.getAll().then(function(res) {
                if (res.success) {
                  me.model.pages = res.model.pages;
                }
              });
              window.info.done(Kooboo.text.info.delete.success);
            } else {
              window.info.done(Kooboo.text.info.delete.fail);
            }
          });
      }
    },
    watch: {
      importFrom: function(value) {
        if (value == "file") this.$refs.importForm.clearValid();
      },
      showRouterManagerModal: function(value) {
        if (!value) return;
        var me = this;
        Kooboo.Page.getDefaultRoute().then(function(res) {
          if (res.success) {
            me.routerModel = res.model;
            if (
              me.routerModel.startPage == Kooboo.Guid.Empty &&
              me.model.pages &&
              me.model.pages.length
            ) {
              me.routerModel.startPage = me.model.pages[0].id;
            }
          }
        });
      },
      showCopyModal: function(value) {
        if (value) {
          if (this.selectedRows && this.selectedRows.length != 1) return;
          var row = this.selectedRows[0];
          this.copyModel.id = row.id;
          var pageName = row.name || "";
          if (pageName.indexOf(".") > -1) {
            var _temp = pageName.split(".");
            _temp[0] = _temp[0] + "_Copy";
            pageName = _temp.join(".");
          } else {
            pageName += "_Copy";
          }
          this.copyModel.name = pageName;
          this.copyModel.url = "/" + pageName;
        } else {
          this.$refs.copyForm.clearValid();
        }
      },
      "importModel.pageUrl": function(val) {
        var path = /\w[^/]+:\/\/[\w\.]+:?\d*(.[^\?&]+)/.exec(val.trim());
        var name = "";
        if (!path) name = "";
        else if (!path[1]) name = "";
        else if (path[1].startsWith("/")) name = path[1];
        else if (path[1].indexOf("/") > -1) name = "/";
        this.importModel.name = name;
      },
      showImportModal: function() {
        this.importModel.pageUrl = "";
        this.importModel.name = "";
        this.$refs.importForm.clearValid();
      },
      routerModel: {
        handler: function(val) {
          if (val.notFound == val.startPage) {
            val.notFound = Kooboo.Guid.Empty;
          }
          if (val.error === val.startPage) {
            val.error = Kooboo.Guid.Empty;
          }
        },
        deep: true
      },
      "routerModel.notFound": function(val) {
        if (val != Kooboo.Guid.Empty && this.routerModel.error == val) {
          this.routerModel.error = Kooboo.Guid.Empty;
        }
      },
      "routerModel.error": function(val) {
        if (val != Kooboo.Guid.Empty && this.routerModel.notFound == val) {
          this.routerModel.notFound = Kooboo.Guid.Empty;
        }
      }
    }
  });
</script>
